<template>
  <view class="login-container" :class="{ compact: isCompact }">
    <!-- App Logo -->
    <view class="logo-section">
      <view class="logo-icon">
        <text class="logo-text">📊</text>
      </view>
      <text class="app-title">代账记账助手</text>
      <text class="app-subtitle">专业财务记账管理平台</text>
    </view>
    
    <!-- Login Form -->
    <view class="login-form">
      <view class="form-item">
        <text class="form-label">用户名</text>
        <view class="input-wrapper">
          <text class="input-icon">👤</text>
          <input 
            v-model="form.username" 
            placeholder="请输入用户名"
            class="form-input"
            maxlength="20"
          />
        </view>
      </view>
      
      <view class="form-item">
        <view class="label-row">
          <text class="form-label">密码</text>
          <text class="forgot-password">忘记密码?</text>
        </view>
        <view class="input-wrapper">
          <text class="input-icon">🔒</text>
          <input 
            v-model="form.password" 
            placeholder="请输入密码"
            password="true"
            class="form-input"
            maxlength="20"
            @confirm="handleLogin"
          />
          <text class="toggle-password" @click="togglePasswordVisibility">👁</text>
        </view>
      </view>
      
      <view class="form-item">
        <text class="form-label">图形验证码</text>
        <view class="captcha-wrapper">
          <view class="input-wrapper captcha-input-wrapper">
            <text class="input-icon">🔑</text>
            <input 
              v-model="form.captcha" 
              placeholder="请输入验证码"
              class="form-input"
              maxlength="4"
            />
          </view>
          <view class="captcha-image" @click="getCaptcha">
            <image :src="captchaImage" mode="aspectFit" v-if="captchaImage" />
            <text v-else class="captcha-placeholder">点击获取</text>
          </view>
        </view>
      </view>
      
      <view class="checkbox-row">
        <checkbox-group @change="onRememberChange">
          <label class="checkbox-label">
            <checkbox value="remember" :checked="rememberMe" />
            <text class="checkbox-text">记住我</text>
          </label>
        </checkbox-group>
      </view>
      
      <button 
        class="login-btn"
        :disabled="loading"
        @click="handleLogin"
      >
        <text class="btn-text">{{ loading ? '登录中...' : '登录' }}</text>
        <text class="btn-arrow">→</text>
      </button>
      
      <view class="register-link">
        <text class="register-text">还没有账号？</text>
        <text class="register-btn" @click="goToRegister">立即注册</text>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
  import request from '@/utils/request'

  const instance = getCurrentInstance()
  const store = instance.appContext.config.globalProperties.$store
  
  // 响应式数据
  const loading = ref(false)
  const captchaImage = ref('')
  const captchaId = ref('')
  const mockCaptchaCode = ref('') // 模拟验证码
  const rememberMe = ref(false)
  const showPassword = ref(false)
  const isCompact = ref(false)
  const form = reactive({
    username: '',
    password: '',
    captcha: ''
  })

  // 页面加载时执行
  onMounted(() => {
    // 小屏适配：根据屏幕高度开启紧凑模式
    const info = uni.getSystemInfoSync()
    // 以竖屏高度 <= 680dp 作为紧凑阈值（iPhone 8/SE等）
    isCompact.value = info.windowHeight <= 680

    getCaptcha()
    checkLogin()
  })
  
  // 检查登录状态
  const checkLogin = () => {
    const token = uni.getStorageSync('token')
    const userInfo = uni.getStorageSync('userInfo')
    
    if (token && userInfo) {
      // 恢复登录状态到store
      store.user.checkLoginStatus()
      // 如果已登录，直接跳转到首页
      setTimeout(() => {
        redirectToHome()
      }, 500)
    }
  }
  
  // 跳转到首页
  const redirectToHome = () => {
    uni.reLaunch({
      url: '/pages/home/index'
    })
  }
  
  // 获取验证码
  const getCaptcha = async () => {
    try {
      const response = await request.get('/auth/captcha', {}, { hideLoading: true })
      captchaImage.value = response.data.captcha_image
      captchaId.value = response.data.captcha_id
    } catch (error) {
      console.error('获取验证码失败，使用模拟验证码:', error)
      // 暂时使用模拟验证码
      generateMockCaptcha()
    }
  }
  
  // 生成模拟验证码
  const generateMockCaptcha = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    let code = ''
    for (let i = 0; i < 4; i++) {
      code += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    captchaId.value = 'mock-' + Date.now()
    captchaImage.value = 'data:image/svg+xml;base64,' + btoa(`
      <svg width="100" height="40" xmlns="http://www.w3.org/2000/svg">
        <rect width="100" height="40" fill="#f0f0f0"/>
        <text x="50%" y="50%" text-anchor="middle" dy="0.3em" font-family="Arial" font-size="16" fill="#333">${code}</text>
      </svg>
    `)
    // 存储验证码用于验证
    mockCaptchaCode.value = code
  }
  
  // 处理登录
  const handleLogin = async () => {
    // 表单验证
    if (!form.username.trim()) {
      uni.showToast({
        title: '请输入用户名',
        icon: 'none'
      })
      return
    }
    
    if (form.username.length < 2 || form.username.length > 20) {
      uni.showToast({
        title: '用户名长度在2-20个字符之间',
        icon: 'none'
      })
      return
    }
    
    if (!form.password) {
      uni.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }
    
    if (form.password.length < 6 || form.password.length > 20) {
      uni.showToast({
        title: '密码长度在6-20个字符之间',
        icon: 'none'
      })
      return
    }
    
    if (!form.captcha.trim()) {
      uni.showToast({
        title: '请输入验证码',
        icon: 'none'
      })
      return
    }
    
    if (form.captcha.length !== 4) {
      uni.showToast({
        title: '验证码长度为4位',
        icon: 'none'
      })
      return
    }
    
    if (!captchaId.value) {
      uni.showToast({
        title: '请先获取验证码',
        icon: 'none'
      })
      return
    }
    
    loading.value = true
    
    try {
      // 如果是模拟验证码，先进行本地验证
      if (captchaId.value.startsWith('mock-')) {
        if (form.captcha.toLowerCase() !== mockCaptchaCode.value.toLowerCase()) {
          uni.showToast({
            title: '验证码错误',
            icon: 'none'
          })
          getCaptcha()
          form.captcha = ''
          loading.value = false
          return
        }
      }
      
      const response = await request.post('/auth/login', {
        username: form.username,
        password: form.password,
        captcha_code: form.captcha.toLowerCase(),
        captcha_id: captchaId.value
      })
      
      // 保存登录信息
      store.user.login({
        token: response.data.token,
        userInfo: response.data.user
      })
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      // 跳转到首页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/home/index'
        })
      }, 1000)
      
    } catch (error) {
      console.error('登录失败:', error)
      // 刷新验证码
      getCaptcha()
      form.captcha = ''
    } finally {
      loading.value = false
    }
  }
  

  
  // 切换密码可见性
  const togglePasswordVisibility = () => {
    showPassword.value = !showPassword.value
    // 这里可以动态改变input的type，但uni-app中需要其他方式实现
  }
  
  // 记住我选择变化
  const onRememberChange = (e) => {
    rememberMe.value = e.detail.value.includes('remember')
  }
  
  // 跳转到注册页面
  const goToRegister = () => {
    uni.showToast({
      title: '注册功能开发中',
      icon: 'none'
    })
  }
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  padding: 40rpx 32rpx;
  box-sizing: border-box;
  overflow: hidden;
}
.login-container.compact {
  padding: 24rpx 24rpx;
}

// Logo Section
.logo-section {
  text-align: center;
  margin-top: 40rpx;
  margin-bottom: 60rpx;
}
.login-container.compact .logo-section {
  margin-top: 16rpx;
  margin-bottom: 24rpx;
}
  
  .logo-icon {
    width: 120rpx;
    height: 120rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 40rpx;
    box-shadow: 0 8rpx 30rpx rgba(102, 126, 234, 0.3);
    
    .logo-text {
      font-size: 60rpx;
    }
  }
  
  .app-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #2c3e50;
    margin-bottom: 16rpx;
  }
  
  .app-subtitle {
    font-size: 28rpx;
    color: #7f8c8d;
  }

// Login Form
.login-form {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 48rpx 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}
.login-container.compact .login-form {
  padding: 36rpx 28rpx;
}
  
  .form-item {
    margin-bottom: 40rpx;
    
    .form-label {
      display: block;
      font-size: 28rpx;
      color: #2c3e50;
      margin-bottom: 16rpx;
      font-weight: 500;
    }
    
    .label-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16rpx;
      
      .forgot-password {
        font-size: 26rpx;
        color: #667eea;
      }
    }
    
    .input-wrapper {
      position: relative;
      display: flex;
      align-items: center;
      height: 88rpx;
      background: #f8f9fa;
      border-radius: 12rpx;
      border: 2rpx solid #e9ecef;
      transition: border-color 0.3s;
      
      &:focus-within {
        border-color: #667eea;
        background: #ffffff;
      }
      
      .input-icon {
        font-size: 32rpx;
        margin: 0 24rpx 0 20rpx;
        color: #95a5a6;
      }
      
      .form-input {
        flex: 1;
        height: 100%;
        border: none;
        background: transparent;
        font-size: 28rpx;
        color: #2c3e50;
        
        &::placeholder {
          color: #bdc3c7;
        }
      }
      
      .toggle-password {
        font-size: 32rpx;
        padding: 0 20rpx;
        color: #95a5a6;
      }
    }
    
    .captcha-wrapper {
      display: flex;
      gap: 20rpx;
      
      .captcha-input-wrapper {
        flex: 1;
      }
      
      .captcha-image {
        width: 200rpx;
        height: 88rpx;
        border-radius: 12rpx;
        background: #f8f9fa;
        border: 2rpx solid #e9ecef;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        
        image {
          width: 100%;
          height: 100%;
        }
        
        .captcha-placeholder {
          font-size: 24rpx;
          color: #95a5a6;
        }
      }
    }
  }
  
  .checkbox-row {
    margin: 30rpx 0;
    
    .checkbox-label {
      display: flex;
      align-items: center;
      
      .checkbox-text {
        font-size: 26rpx;
        color: #7f8c8d;
        margin-left: 16rpx;
      }
    }
  }
  
  .login-btn {
    width: 100%;
    height: 96rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    border: none;
    border-radius: 48rpx;
    font-size: 32rpx;
    font-weight: 600;
    margin: 40rpx 0 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8rpx 30rpx rgba(102, 126, 234, 0.3);
    transition: all 0.3s;
    
    .btn-text {
      margin-right: 16rpx;
    }
    
    .btn-arrow {
      font-size: 28rpx;
      font-weight: normal;
    }
    
    &:disabled {
      background: #bdc3c7;
      box-shadow: none;
    }
    
    &:active:not(:disabled) {
      transform: translateY(2rpx);
      box-shadow: 0 4rpx 15rpx rgba(102, 126, 234, 0.3);
    }
  }
  
  .divider {
    text-align: center;
    margin: 40rpx 0 30rpx;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 2rpx;
      background: #e9ecef;
    }
    
    .divider-text {
      background: #ffffff;
      padding: 0 30rpx;
      font-size: 26rpx;
      color: #95a5a6;
      position: relative;
      z-index: 1;
    }
  }
  
  .social-login {
    display: flex;
    justify-content: center;
    gap: 40rpx;
    margin-bottom: 40rpx;
    
    .social-btn {
      width: 88rpx;
      height: 88rpx;
      border-radius: 50%;
      background: #f8f9fa;
      border: 2rpx solid #e9ecef;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;
      
      .social-icon {
        font-size: 36rpx;
      }
      
      &.wechat {
        background: #07c160;
        border-color: #07c160;
        
        .social-icon {
          color: #ffffff;
        }
      }
      
      &:active {
        transform: scale(0.95);
      }
    }
  }
  
  .register-link {
    text-align: center;
    
    .register-text {
      font-size: 26rpx;
      color: #7f8c8d;
      margin-right: 8rpx;
    }
    
    .register-btn {
      font-size: 26rpx;
      color: #667eea;
      font-weight: 500;
    }
  }
  /* Compact overrides */
  .login-container.compact .logo-icon { width: 88rpx; height: 88rpx; margin: 0 auto 24rpx; }
  .login-container.compact .app-title { font-size: 40rpx; }
  .login-container.compact .app-subtitle { font-size: 24rpx; }
  .login-container.compact .login-form .input-wrapper { height: 76rpx; }
  .login-container.compact .login-form .captcha-image { width: 160rpx; height: 76rpx; }
  .login-container.compact .login-form .form-item { margin-bottom: 28rpx; }
  .login-container.compact .login-btn { height: 84rpx; margin: 24rpx 0 16rpx; }
  .login-container.compact .divider, .login-container.compact .social-login { display: none; }
  .login-container.compact .register-link { margin-top: 8rpx; }
</style> 